package com.shawn.dubbo.api;

import com.shawn.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@DubboService
public class LocationApiImpl implements LocationApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上传地图信息
     *
     * @param userId             用户id
     * @param longitude          经度
     * @param latitude           纬度
     * @param addressDescription 地址描述
     * @return {@link Boolean}
     */
    @Override
    public Boolean uploadMapInfo(Long userId, Double longitude, Double latitude, String addressDescription) {
        try {
            //查询当前用户是否为未上传用户
            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(userId));
            UserLocation oldLocation = mongoTemplate.findOne(query, UserLocation.class);
            //构造对象
            UserLocation userLocation = new UserLocation();

            if (oldLocation!=null){
                Update update = new Update();
                //经纬度信息
                update.set("location",new GeoJsonPoint(longitude,latitude))
                        //地名
                        .set("address",addressDescription)
                        //更新时间
                        .set("updated",System.currentTimeMillis())
                        //上次更新时间
                        .set("lastUpdated",oldLocation.getUpdated());
                userLocation.setLastUpdated(oldLocation.getUpdated());
                mongoTemplate.updateFirst(query,update,UserLocation.class);
            }else {
                userLocation.setUserId(userId);
                userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
                userLocation.setAddress(addressDescription);
                userLocation.setUpdated(System.currentTimeMillis());
                userLocation.setCreated(System.currentTimeMillis());
                userLocation.setLastUpdated(System.currentTimeMillis());
                mongoTemplate.save(userLocation);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Long> searchNearlyPeople(Long userId, String gender, String distance) {
        //查询当前用户位置
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation==null){
            return null;
        }
        //构建查询
        //1 原点
        GeoJsonPoint point = userLocation.getLocation();
        //2 半径 distance
        Distance dis = new Distance(Double.parseDouble(distance)/1000, Metrics.KILOMETERS);
        //3 圆
        Circle circle = new Circle(point, dis);

        //构造查询
        Query nearQuery = new Query();
        nearQuery.addCriteria(Criteria.where("location").withinSphere(circle))
                .addCriteria(Criteria.where("userId").ne(userId))
                .fields().include("userId");
        //调用
        List<UserLocation> locations = mongoTemplate.find(nearQuery, UserLocation.class);
        return locations.stream().map(UserLocation::getUserId).collect(Collectors.toList());
    }

    @Override
    public List<Double> getNowLocation(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (Objects.isNull(userLocation)){
            return Objects.requireNonNull(mongoTemplate.findOne(new Query(Criteria.where("userId").is(106)), UserLocation.class)).getLocation().getCoordinates();
        }
        return userLocation.getLocation().getCoordinates();
    }
}
